#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# chm-thumbnailer.py: Extract image from chm
#

# Based on work by:
#  monraaf: http://ubuntu-ky.ubuntuforums.org/member.php?u=536089
#           http://ubuntuforums.org/showthread.php?t=1159569
#  George Dumitrescu: https://launchpad.net/~geod
#           https://launchpad.net/deb-thumbnailer

__author__ = "Neko"
__license__ = 'GPL http://www.gnu.org/licenses/gpl.txt'
__version__ = '0.2.2.0'

'''
0.2.0.0     First full working version
0.2.1.0     Line image heuristic
0.2.2.0     Home file is image itself
TODO
0.4.0.0     Misconstructed HTML (HTMLParser to BeautifulSoup?)
0.4.1.0     HTML Redirect
'''

import sys, urllib

from HTMLParser import HTMLParser
from StringIO import StringIO

import chm.chm

from PIL import Image


def _absname(home, img):
    
    if img[0] != '/':
        absname = '/'.join(home.split('/')[0:-1]) + '/' + img
    else:
        absname = img
        
    return absname, img.split('/')[-1]
    

class CHMParser(HTMLParser):

    def __init__(self, chmObj):
        HTMLParser.__init__(self)
        
        self._chmObj = chmObj
        self._home = chmObj.home
        
        self._size = 0
        self._images = []
        self.Image = None

    def handle_starttag(self, tag, attrs):
        if tag != 'img':
            return

        for name, value in attrs:
            if name == 'src':   
                image = value
        absname, basename = _absname(self._home, image)
        
        if absname in self._images:
            return

        self._images.append(absname)
        nok, ui = self._chmObj.ResolveObject(absname)
        if nok != 0:
            return
            
        nimage = Image.open(StringIO(self._chmObj.RetrieveObject(ui)[1]))

        width, length = nimage.size

        if min(width,length) * 2 < max(width, length):
            return
        
        if width * length > self._size:
            self.Image = nimage
            self._size = width * length


def parseCHM(chmObj):
    chmPrs = CHMParser(chmObj)

    ok, ui = chmObj.ResolveObject(chmObj.home)
    if ok == 0:
        if chmObj.home.endswith(('jpg','gif','bmp')):
            return Image.open(StringIO(chmObj.RetrieveObject(ui)[1]))
        else:
            chmPrs.feed(chmObj.RetrieveObject(ui)[1])
            return chmPrs.Image          


if __name__ == "__main__":
    
    chmObj = chm.chm.CHMFile()    

    if len(sys.argv) != 4:
        print "CHM thumbnailer %s" % __version__
        print "Usage: %s input output size" % sys.argv[0]
        sys.exit(-1) 

    input = urllib.url2pathname(sys.argv[1]).replace('file://', '')
    output = urllib.url2pathname(sys.argv[2]).replace('file://', '')
    size = int(sys.argv[3])

    if not chmObj.LoadCHM(input):
        print('Error opening CHM file')
        sys.exit(-1)

    Image = parseCHM(chmObj)
    if Image:
        Image.thumbnail((size, size))
        Image.save(output, 'PNG')
